using Godot;
using System;

public partial class NStoreInventory : Control
{
	public static string STORE_CUR_BUY_ITEM = "STORE_CUR_BUY_ITEM";
	Panel mConfirmPanel;
	Label mConfirmMoney;
	// Called when the node enters the scene tree for the first time.
	public override void _Ready()
	{
		mConfirmMoney = GetNode<Label>("Panel2/Label");
		mConfirmPanel = GetNode<Panel>("Panel2");
		mConfirmPanel.Visible = false;
		GridContainer gc = GetNode<GridContainer>("Panel/GridContainer");
		foreach (NStoreInventoryPanel p in gc.GetChildren())
		{
			p.buyItem += (item) => _buyItem(item);
		}
	}
	void _on_button_pressed()
	{
		//确认
		NItem item = GetTree().GetFirstNodeInGroup(STORE_CUR_BUY_ITEM) as NItem;
		NInventory inventory = GetTree().GetFirstNodeInGroup(nameof(NInventory)) as NInventory;
		if (inventory != null && item != null)
		{
			//钱够不够
			if (inventory.mMoney >= item.mItem.mMoney)
			{
				if (inventory.pickItem(item.mItem.Duplicate(true) as CItem))
				{
					inventory.mMoney -= item.mItem.mMoney;
					mConfirmPanel.Visible = false;
					item.RemoveFromGroup(STORE_CUR_BUY_ITEM);
				}
			}
		}
	}

	void _on_button_2_pressed()
	{
		NItem item = GetTree().GetFirstNodeInGroup(STORE_CUR_BUY_ITEM) as NItem;
		//放弃
		mConfirmPanel.Visible = false;
		if (item != null)
		{
			item.RemoveFromGroup(STORE_CUR_BUY_ITEM);
		}
	}

	void _buyItem(NItem item)
	{
		//当前没有正在购买的物品
		if (mConfirmPanel.Visible == false)
		{
			mConfirmMoney.Text = string.Format("需要 {0} 金钱", item.mItem.mMoney);
			NInventory inventory = GetTree().GetFirstNodeInGroup(nameof(NInventory)) as NInventory;
			if (inventory != null)
			{
				mConfirmPanel.Visible = true;
				item.AddToGroup(STORE_CUR_BUY_ITEM);
			}
		}
	}

	// Called every frame. 'delta' is the elapsed time since the previous frame.
	public override void _Process(double delta)
	{
	}
}
